<template>
  <van-popup
    v-model:show="showLocal"
    position="right"
    :round="true"
    :style="{ width: '65%', height: '100%', maxWidth: '300px' }"
    @close="handleClose"
  >
    <div class="filter-content">
      <!-- 标题栏 -->
      <div class="filter-header">
        <h2>筛选</h2>
      </div>

      <!-- 筛选内容区 -->
      <div class="filter-body">
        <!-- 季节筛选 -->
        <div class="filter-section">
          <div class="filter-section-header">
            <div class="filter-section-header-icon">
              <img src="/src/assets/icons/ico-leaf.svg" alt="" />
              <span style="font-size: 15px">季节</span>
            </div>
            <span class="select-all-text">全部</span>
          </div>
          <div class="filter-options">
            <div class="season-options-row">
              <div
                v-for="season in seasons"
                :key="season"
                :class="[
                  'season-option-btn',
                  selectedSeasons.includes(season) ? 'selected' : '',
                ]"
                @click="toggleSeason(season)"
              >
                {{ season }}
              </div>
            </div>
          </div>
        </div>

        <!-- 分类筛选 -->
        <div class="filter-section">
          <div class="filter-section-header">
            <div class="filter-section-header-icon">
              <img src="/src/assets/icons/type.svg" alt="" />
              <span style="font-size: 15px">分类</span>
            </div>
            <span class="select-all-text"> 全部 </span>
          </div>
          <div class="category-options-grid">
            <div
              v-for="(category, categoryName) in categories"
              :key="categoryName"
              :class="[
                'category-option-btn',
                selectedCategories.includes(categoryName) ? 'selected' : '',
              ]"
              @click="toggleCategory(categoryName)"
            >
              {{ categoryName }}({{ category.length }})
            </div>
          </div>
        </div>

        <!-- 颜色筛选 -->
        <div class="filter-section">
          <div class="filter-section-header">
            <div class="filter-section-header-icon">
              <img src="/src/assets/icons/color.svg" alt="" />
              <span style="font-size: 15px">颜色</span>
            </div>
            <span class="select-all-text"> 全部 </span>
          </div>
          <div class="color-options">
            <div
              v-for="color in colorMap"
              :key="color.name"
              :class="[
                'color-item',
                { selected: selectedColors.includes(color.name) },
              ]"
              @click="toggleColor(color.name)"
            >
              <div
                class="color-swatch"
                :style="{ backgroundColor: color.value }"
              ></div>
              <div class="color-name">{{ color.name }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部确认按钮 -->
      <div class="filter-footer">
        <div class="footer-btn-group">
          <button class="reset-btn" @click="resetFilters">重置</button>
          <button class="confirm-btn" @click="handleConfirm">确定</button>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, watch } from "vue";
import { colorMap } from "../utils/colors";

// Props
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  categories: {
    type: Object,
    default: () => ({
      上衣: [],
      下装: [],
      鞋子: [],
      裙子: [],
      外套: [],
      配饰: [],
      运动装: [],
      家居服: [],
    }),
  },
});

// 创建本地ref来存储show状态
const showLocal = ref(props.show);

// Emits
const emit = defineEmits(["update:show", "apply", "close"]);

// 监听prop变化，更新本地ref
watch(
  () => props.show,
  (newValue) => {
    showLocal.value = newValue;
  }
);

// 监听本地ref变化，通知父组件
watch(showLocal, (newValue) => {
  emit("update:show", newValue);
});

// 筛选选项
const seasons = ["春", "夏", "秋", "冬"];

// 选中的筛选条件
const selectedSeasons = ref([]);
const selectedCategories = ref([]);
const selectedColors = ref([]);

// 存储已确认的筛选条件（用于恢复状态）
const confirmedSeasons = ref([]);
const confirmedCategories = ref([]);
const confirmedColors = ref([]);

// 标记是否有未确认的更改
const hasUnsavedChanges = ref(false);

// 监听show变化，处理弹窗显示/隐藏逻辑
watch(
  () => props.show,
  (newValue) => {
    if (newValue) {
      // 弹窗打开时，恢复已确认的筛选条件
      selectedSeasons.value = [...confirmedSeasons.value];
      selectedCategories.value = [...confirmedCategories.value];
      selectedColors.value = [...confirmedColors.value];
      hasUnsavedChanges.value = false;
    }
  }
);

// 处理弹窗关闭事件
const handleClose = () => {
  // 点击遮罩层关闭时，如果有未确认的更改，则清空
  if (hasUnsavedChanges.value) {
    selectedSeasons.value = [];
    selectedCategories.value = [];
    selectedColors.value = [];
    hasUnsavedChanges.value = false;
  }
  emit("close");
};

// 切换单个季节的选中状态
const toggleSeason = (season) => {
  if (selectedSeasons.value.includes(season)) {
    // 如果已选中，则取消选中
    selectedSeasons.value = selectedSeasons.value.filter((s) => s !== season);
  } else {
    // 如果未选中，则添加选中
    selectedSeasons.value.push(season);
  }
  hasUnsavedChanges.value = true;
};

// 切换单个分类的选中状态
const toggleCategory = (categoryName) => {
  if (selectedCategories.value.includes(categoryName)) {
    // 如果已选中，则取消选中
    selectedCategories.value = selectedCategories.value.filter(
      (cat) => cat !== categoryName
    );
  } else {
    // 如果未选中，则添加选中
    selectedCategories.value.push(categoryName);
  }
  hasUnsavedChanges.value = true;
};

// 切换颜色选择
const toggleColor = (colorName) => {
  const index = selectedColors.value.indexOf(colorName);
  if (index > -1) {
    selectedColors.value.splice(index, 1);
  } else {
    selectedColors.value.push(colorName);
  }
  hasUnsavedChanges.value = true;
};

// 重置筛选条件
const resetFilters = () => {
  selectedSeasons.value = [];
  selectedCategories.value = [];
  selectedColors.value = [];
  confirmedSeasons.value = [];
  confirmedCategories.value = [];
  confirmedColors.value = [];
  hasUnsavedChanges.value = false;

  // 同步传递清空后的筛选数据
  emit("apply", {
    seasons: [],
    categories: [],
    colors: [],
  });
};

// 应用筛选条件
const handleConfirm = () => {
  const filters = {
    seasons: selectedSeasons.value,
    categories: selectedCategories.value,
    colors: selectedColors.value,
  };

  // 保存已确认的筛选条件
  confirmedSeasons.value = [...selectedSeasons.value];
  confirmedCategories.value = [...selectedCategories.value];
  confirmedColors.value = [...selectedColors.value];
  hasUnsavedChanges.value = false;

  // 传递筛选数据
  emit("apply", filters);
  emit("update:show", false);
};
</script>

<style scoped>
.filter-section-header-icon {
  display: flex;
  align-items: center;
  gap: 5px;
}
.filter-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.filter-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  /* 隐藏滚动条 */
  scrollbar-width: none;
  -ms-overflow-style: none;
  /* 兼容h5 */
  overflow: -moz-scrollbars-none;
}
.filter-body::-webkit-scrollbar {
  display: none;
}

.filter-section {
  margin-bottom: 25px;
}

.filter-section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.filter-section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

/* 分类选项网格布局 */
.category-options-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

/* 分类选项按钮样式 */
.category-option-btn {
  padding: 4px 16px;
  border-radius: 20px;
  background-color: #f0f0f0;
  color: #666;
  font-size: 12px;
  text-align: center;
  cursor: default;
  user-select: none;
  white-space: nowrap;
}

/* 选中状态的分类选项按钮样式 */
.category-option-btn.selected {
  background-color: #6c63ff;
  color: white;
}

/* 文本类型"全部"选项样式 */
.select-all-text {
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

/* 季节选项行样式 */
.season-options-row {
  display: flex;
  /* 分散对齐 */

  width: 100%;
  justify-content: space-between;
}

/* 季节选项按钮样式 */
.season-option-btn {
  padding: 4px 16px;
  border-radius: 20px;
  background-color: #f0f0f0;
  color: #666;
  font-size: 12px;
  text-align: center;
  cursor: default;
  user-select: none;
  white-space: nowrap;
}

/* 选中状态的季节选项按钮样式 */
.season-option-btn.selected {
  background-color: #6c63ff;
  color: #fff;
}

/* 文本类型的"全部"选项样式 */
.select-all-text {
  font-size: 12px;
  color: #999;
}

/* .filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
} */

.van-checkbox {
  margin-bottom: 10px;
  font-size: 14px;
}

.color-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 10px 0;
}

.color-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 2px 6px 2px 2px;
  border-radius: 20px;
  background-color: #f0f0f0;
  cursor: pointer;
  transition: all 0.3s;
  width: fit-content;
}

.color-item.selected {
  background-color: #e6f7ff;
}

.color-swatch {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  /* border: 2px solid #fff; */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* .color-item.selected .color-swatch {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
} */

.color-name {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

/* .color-item.selected .color-name {
  color: #1890ff;
} */

.filter-footer {
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}
.footer-btn-group {
  background-color: #f0f0f0;
  display: flex;

  border-radius: 8px;
}
.reset-btn {
  width: 50%;
  border: none;
  background: none;
  color: #000000;
  font-size: 15px;
  cursor: pointer;
}
.confirm-btn {
  width: 50%;
  padding: 12px;
  background-color: #000000;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.confirm-btn:hover {
  background-color: #40a9ff;
}
</style>
